/*
 * @Description:
 * @Date: 2023-10-08 13:56:18
 * @LastEditTime: 2023-11-01 09:29:07
 */

import * as Cesium from 'cesium';

// enum limType  {
//   1:import("../../")
// }
export default class DrawPoints {
	constructor(options) {
		this.layer = new Cesium.CustomDataSource('MyPoints');
		this.handler = undefined;
	}
	/**
	 * 添加鼠标点击事件
	 * @param {Cesium.Viewer} viewer 目标地图
	 */
	bindAction(viewer) {
		if (!this.handler) {
			this.handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
		}
		this.handler.setInputAction(async click => {
			let earthPosition = undefined;
			// 球面
			console.log(click.position);

			if (viewer.terrainProvider instanceof Cesium.EllipsoidTerrainProvider) {
				earthPosition = viewer.scene.camera.pickEllipsoid(click.position);
			}
			// 地形
			else {
				const ray = viewer.camera.getPickRay(click.position);
				earthPosition = viewer.scene.globe.pick(ray, viewer.scene);
			}
			if (Cesium.defined(earthPosition)) {
				const entity = this.createPoint(earthPosition);

				let cartographic = Cesium.Cartographic.fromCartesian(earthPosition);
				let lng = Cesium.Math.toDegrees(cartographic.longitude); // 经度
				let lat = Cesium.Math.toDegrees(cartographic.latitude); // 纬度
				let alt = cartographic.height; // 高度，椭球面height永远等于0
				let coordinate = {
					longitude: Number(lng.toFixed(6)),
					latitude: Number(lat.toFixed(6)),
					altitude: Number(alt.toFixed(2))
				};

				db('dzbInfo')
					.insert({
						name: '点位1',
						lat: coordinate.latitude,
						lng: coordinate.longitude,
						rate: '100',
						level: '1'
					})
					.then(() => {
						console.log('新增成功');
					});
				this.layer.entities.add(entity);
			}
		}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
	}
	/**
	 * 创建点
	 * @param {Cesium.Cartesian3} worldPosition A 3D Cartesian point.
	 * @return {Cesium.Entity} 点实体
	 */
	createPoint(worldPosition, name, avatar, id, data) {
		const point = new Cesium.Entity({
			id,
			position: worldPosition,
			// 图标
			billboard: {
				image: avatar,
				width: 50,
				height: 50
			},
			label: {
				//文字标签
				text: name,
				font: '20px sans-serif',
				style: Cesium.LabelStyle.FILL,
				// 对齐方式(水平和竖直)
				horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
				verticalOrigin: Cesium.VerticalOrigin.CENTER,
				pixelOffset: new Cesium.Cartesian2(0, -50),
				showBackground: true,
				backgroundColor: new Cesium.Color.fromBytes(0, 70, 24)
			},
			monitoItems: {
				data
			}
		});

		return point;
	}
	/**
	 * 添加图层
	 * @param {Cesium.Viewer} viewer 目标地图
	 */
	addToMap(viewer) {
		viewer.dataSources.add(this.layer);
	}
}
